/*
 * Copyright 2020-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sagacity.framework.api.model.response;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sagacity.framework.api.constant.ResponseCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.slf4j.MDC;

/**
 * @author xingyun
 * @date 2020-07-04 14:13
 */
@Data
@ApiModel(description = "响应对象")
public class ResponseEntity<T> {
    @ApiModelProperty("响应码")
    private String code;

    @ApiModelProperty("响应消息")
    private String msg;
    /**
     * 数据
     */
    @ApiModelProperty("数据")
    private T data;

    @ApiModelProperty("请求链路ID")
    private String traceId;

    ResponseEntity(){this.traceId = MDC.get("traceId");}

    ResponseEntity(ResponseCode responseCode){
        this.code = ResponseCode.SUCCESS.getCode();
        this.msg = ResponseCode.SUCCESS.getMsg();
        this.traceId = MDC.get("traceId");
    }

    /**
     * 创建响应对象
     * @param <T> 泛型
     * @return 响应对象
     */
    public static <T>  ResponseEntity<T> create(){
        return new ResponseEntity<>();
    }

    public static <T>  ResponseEntity<T> ok(T data){
        ResponseEntity<T> resp = ok();
        resp.setData(data);
        return resp;
    }

    @JsonIgnore
    public static <T> ResponseEntity<T> ok(){
        return new ResponseEntity<>(ResponseCode.SUCCESS);

    }

    public void fail(){
        this.code = ResponseCode.FAIL.getCode();
        this.msg = ResponseCode.FAIL.getMsg();
    }

    public void fail(String message){
        this.code = ResponseCode.FAIL.getCode();
        this.msg = message;
    }

    public ResponseEntity<T> setData(T data){
        this.data = data;
        return this;
    }

    @JsonIgnore
    public boolean isOk() {
        return ResponseCode.SUCCESS.getCode().equals(this.code);
    }
}
